package com.wk.database;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DatabaseConnector {
	private volatile static Connection connection = null;
	public synchronized static void connect(String host, String userName, String password) throws ClassNotFoundException, SQLException {
		if (connection == null) {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(
					"jdbc:mysql://" + host + "?useUnicode=true&characterEncoding=utf-8", userName,
					password);
		}
	}

	
	public static Connection getConnection() {
		return connection;
	}
	public static Connection initConnection() {
		String filePath = "info/mysql.properties";
		Properties databaseInfo = new Properties();
		File file = new File(filePath);
		try {
			InputStream filein = new FileInputStream(file);
			databaseInfo.load(filein);
			String  host = databaseInfo.getProperty("address");
			String  userName = databaseInfo.getProperty("userName");
			String password = databaseInfo.getProperty("password");
			connect(host,userName,password);
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println(e.getStackTrace()[0].getLineNumber());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getStackTrace()[0].getLineNumber());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return connection;
	}

	
}
